package com.jd.system.service.impl;

import com.jd.system.domain.Role;
import com.jd.system.mapper.RoleMapper;
import com.jd.system.service.IRoleService;
import com.jd.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 业务实现类：
 */
@Service
public class RoleServiceImpl extends BaseServiceImpl<Role> implements IRoleService {
    @Autowired
    private RoleMapper roleMapper;

    /**
     * 添加重构
     * @param role
     */
    @Transactional
    @Override
    public void save(Role role) {
        //获取Role自增id
        super.save(role);
        Long roleId = role.getId();
        //角色分配权限
        List<Long> permissions = role.getPermissions();
        if (permissions.size() > 0){
            roleMapper.saveRolePermissions(role.getId(),permissions);
        }
        //角色分配菜单
        List<Long> menus = role.getMenus();
        if (menus.size() > 0) {
            roleMapper.saveRoleMenus(role.getId(),menus);
        }

    }
    @Transactional
    @Override
    public void remove(Long id) {
        //删除中间表 role_permissions
        roleMapper.removeRolePermissionByRoleId(id);
        //删除中间表 role_menu
        roleMapper.removeRoleMenuByRoleId(id);
        //删除角色
        super.remove(id);
    }
    @Transactional
    @Override
    public void update(Role role) {
        Long roleId = role.getId();
        //删除中间表 role_permissions
        roleMapper.removeRolePermissionByRoleId(roleId);
        //删除中间表 role_menu
        roleMapper.removeRoleMenuByRoleId(roleId);
        //删除角色
        roleMapper.remove(roleId);

        //角色分配权限
        List<Long> permissions = role.getPermissions();
        if (permissions.size() > 0){
            roleMapper.saveRolePermissions(roleId,permissions);
        }
        //角色分配菜单
        List<Long> menus = role.getMenus();
        if (menus.size() > 0) {
            roleMapper.saveRoleMenus(roleId,menus);
        }

        super.update(role);
    }
}
